#! /bin/bash
baseUrl="http://app-smarthome.siemens.com.cn/appdownload-guide.html"
outputFile=""
qrcodeUrl=""

showHelp(){
    printf "Encode input cube serial number in a QR Code and save as a PNG image.\n"
    printf "    -o    required    output png image name.\n" 
    printf "    -i    optional    input cube serial number, length eq 18.\n" 
    printf "    -h    optional    display the help message.\n" 
    printf "Example:\n"
    printf "    Cube qr-code: ./dol-qrcode.sh -i 18020770019870097195 -o cube.png\n"
    printf "    Spec qr-code: ./dol-qrcode.sh -o cube.png\n"
}

checkSerialNum(){
    serialNum=$1
    if (( ${#serialNum} == 20 ))
    then
        return 1
    else
        return 0
    fi
}

if (( $# == 4 ))
then
    if [[ $1 == "-i" && $3 == "-o" ]]
    then
        checkSerialNum $2
        if (( $? == 1 ))
        then
            qrcodeUrl=$baseUrl"?id=$2"
            outputFile=$4
        else
            echo "Error: invalid cube serial number."
        fi
    elif [[ $1 == "-o" && $3 == "-i" ]]
    then
        checkSerialNum $4
        if (( $? == 1 ))
        then
            qrcodeUrl=$baseUrl"?id=$4"
            outputFile=$2
        else
            echo "Error: invalid cube serial number."
        fi
    else
        showHelp
    fi
elif (( $# == 2 ))
then
    if [[ $1 == "-o" ]]
    then
        qrcodeUrl=$baseUrl
        outputFile=$2
    else
        showHelp
    fi
else
    showHelp
fi

if (( ${#outputFile} == 0 ))
then
    echo "Error: cube serial number requried."
    exit
fi

if [ ! -x "/usr/local/bin/qrencode" ]
then 
    echo "Error: please install qrencode with homebrew first."
    exit
fi

qrencode -o $outputFile $qrcodeUrl
imagePath=`pwd`"/$outputFile"

if [[ $imagePath == *.png ]]
then
    open $imagePath
else
    echo "Succeed: $imagePath"
fi